package com.concurrent.data.thread.config.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;

import java.nio.charset.Charset;

@Slf4j
public class MyStringRedisSerializer extends StringRedisSerializer {

    private final Charset charset;
    // 可以抽放到配置里面
    private final String prefix = "seckill-shopping:";

    public MyStringRedisSerializer() {
        this(Charset.forName("UTF8"));
    }

    public MyStringRedisSerializer(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }

    @Override
    public byte[] serialize(String string) {
        log.info("------redis序列化key[{}]", string);
        string = prefix + string;
        return super.serialize(string);
    }

    @Override
    public String deserialize(byte[] bytes) {
        String saveKey = new String(bytes, charset);
        log.info("------redis反序列化key[{}]", saveKey);
        int indexOf = saveKey.indexOf(prefix);
        if (indexOf > 0 || indexOf < 0) {
            log.info("------key缺少前缀");
        } else {
            saveKey = saveKey.substring(indexOf);
        }
        log.info("------saveKey:{}", saveKey);
        return (saveKey.getBytes() == null ? null : saveKey);
    }

}
